local obj = {}
local pin = 5
local zeroDeg = 25


local STATUS_START = 2
local STATUS_STOP = 3

local reseting = false
local status = STATUS_STOP

pwm.setup(pin, 50, zeroDeg)

local timer =  tmr.create()
-- 4秒后自动关闭pwm
timer:register(4000, tmr.ALARM_SEMI, function() 
    print("stop pwm")
    pwm.stop(pin)
    status = STATUS_STOP
end)

 -- 频率为50hz，一个周期20ms。转为这里的全占空比为1023
-- 0度  0.5ms
-- 45度 1ms
-- 90度 1.5ms
-- 135度 2ms
-- 180度 2.5ms 占空比为0.125 变为这里的占空比为 128  128-25=103
function obj:SetFx(deg, reset, force)

    if force ~= true and reseting == true then
        return
    end

    local running, mode = timer:state()
    if running == true then
        timer:stop()
    end

    local de = math.ceil(103 * (deg/180)) + zeroDeg
    pwm.setduty(pin, de)

    if status == STATUS_STOP then
        pwm.start(pin)
        status = STATUS_START
    end

    if reset == true then
        reseting = true
        local reset_timer =  tmr.create()
        reset_timer:register(1500, tmr.ALARM_SINGLE, function() 
            reseting = false
       
            local reset_deg = math.min(Config:Get('openDeg'), Config:Get('closeDeg')) + math.ceil(math.abs(Config:Get('openDeg') - Config:Get('closeDeg')) / 2) 
            print(Config:Get('openDeg'), Config:Get('closeDeg'), reset_deg)
            self:SetFx(reset_deg, false, true)
        end)
        reset_timer:start()
    else
        timer:start()
    end

end


function obj:SetOn(switch)
    if tonumber(switch) == 1 then
        self:SetFx(Config:Get('openDeg'), true)
    else
        self:SetFx(Config:Get('closeDeg'), true)
    end
end


function obj:Close()
    pwm.stop(pin)
    pwm.close(pin)
end

function obj:IsReseting()
    return reseting
end

return obj